<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="1200px">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="120px"
      v-loading="formLoading"
      class="invoice-form"
    >
      <!-- 第一行：商家信息 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="商家名称" prop="merchantId">
            <el-select 
              v-model="formData.merchantId" 
              placeholder="请选择商家" 
              filterable 
              :loading="merchantLoading"
              class="w-full"
              popper-class="invoice-form-select-dropdown"
              clearable
              @focus="handleSelectFocus"
              @visible-change="handleVisibleChange"
              @filter-method="handleSearch"
            >
              <el-option
                v-for="item in merchantList"
                :key="item.id"
                :label="item.merchantName"
                :value="item.id"
              />
              <template #dropdown>
                <div class="merchant-select-content">
                  <div v-if="merchantList.length === 0" class="merchant-empty">
                    <el-empty description="暂无数据" />
                  </div>
                  <div v-if="hasMore && !merchantLoading" class="merchant-loading">
                    <el-icon class="is-loading"><Loading /></el-icon>
                    <span class="loading-text">加载更多...</span>
                  </div>
                </div>
              </template>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="发票抬头" prop="invoiceTitle">
            <el-input v-model="formData.invoiceTitle" placeholder="请输入发票抬头" />
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 第二行：税号和发票类型 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="税号" prop="taxNumber">
            <el-input v-model="formData.taxNumber" placeholder="请输入税号" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="发票类型" prop="invoiceType">
            <el-radio-group v-model="formData.invoiceType">
              <el-radio
                v-for="dict in getIntDictOptions(DICT_TYPE.INVOICE_TYPE)"
                :key="dict.value"
                :label="dict.value"
              >
                {{ dict.label }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 第三行：金额和状态 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="开票金额" prop="amount">
            <el-input-number 
              v-model="formData.amount" 
              placeholder="请输入开票金额" 
              :min="0"
              :precision="2"
              :step="0.01"
              controls-position="right"
              class="w-full"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="开票状态" prop="status">
            <el-radio-group v-model="formData.status">
              <el-radio
                v-for="dict in getIntDictOptions(DICT_TYPE.INVOICE_STATUS)"
                :key="dict.value"
                :label="dict.value"
              >
                {{ dict.label }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 第四行：发票代码和发票号码 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="发票代码" prop="invoiceCode">
            <el-input v-model="formData.invoiceCode" placeholder="请输入发票代码" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="发票号码" prop="invoiceNumber">
            <el-input v-model="formData.invoiceNumber" placeholder="请输入发票号码" />
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 第五行：联系人 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="联系人" prop="contactName">
            <el-input v-model="formData.contactName" placeholder="请输入联系人" />
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 查看更多按钮 -->
      <el-form-item>
        <el-button 
          type="text" 
          @click="showMoreFields = !showMoreFields"
          class="view-more-btn"
        >
          <el-icon>
            <ArrowDown v-if="!showMoreFields" />
            <ArrowUp v-if="showMoreFields" />
          </el-icon>
          {{ showMoreFields ? '收起更多信息' : '查看更多信息' }}
        </el-button>
      </el-form-item>

      <!-- 可折叠的更多字段区域 -->
      <el-collapse-transition>
        <div v-show="showMoreFields" class="more-fields">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="联系电话" prop="contactPhone">
                <el-input v-model="formData.contactPhone" placeholder="请输入联系电话" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="联系邮箱" prop="contactEmail">
                <el-input v-model="formData.contactEmail" placeholder="请输入联系邮箱" />
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="开户银行" prop="bankName">
                <el-input v-model="formData.bankName" placeholder="请输入开户银行" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="银行账号" prop="bankAccount">
                <el-input v-model="formData.bankAccount" placeholder="请输入银行账号" />
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="公司地址" prop="companyAddress">
                <el-input v-model="formData.companyAddress" placeholder="请输入公司地址" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="公司电话" prop="companyPhone">
                <el-input v-model="formData.companyPhone" placeholder="请输入公司电话" />
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </el-collapse-transition>

      <!-- 电子发票和备注 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="电子发票" prop="pdfUrl">
            <UploadFile v-model="formData.pdfUrl" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="备注" prop="remark">
            <el-input 
              v-model="formData.remark" 
              type="textarea" 
              :rows="3"
              placeholder="请输入备注" 
              maxlength="200"
              show-word-limit
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { getIntDictOptions, getStrDictOptions, getBoolDictOptions, DICT_TYPE } from '@/utils/dict'
import { InvoiceRecordApi, InvoiceRecordVO } from '@/api/juliang/invoice'
import { MerchantApi } from '@/api/juliang/merchant'
import { MerchantVO } from '@/api/juliang/merchant'
import { Loading, ArrowDown, ArrowUp } from '@element-plus/icons-vue'
import { throttle, debounce } from 'lodash-es'

/** 发票记录 表单 */
defineOptions({ name: 'InvoiceRecordForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const showMoreFields = ref(false) // 是否显示更多字段

// 商家相关状态
const merchantList = ref<MerchantVO[]>([]) // 商家列表
const merchantLoading = ref(false) // 商家列表加载状态
const hasMore = ref(true) // 是否还有更多数据
const loadingNewPage = ref(false) // 标记是否正在加载新页面
const searchKeyword = ref('') // 搜索关键字

const merchantQuery = reactive({
  pageNo: 1,
  pageSize: 10,
  merchantName: undefined as string | undefined
})

const formData = ref({
  id: undefined,
  merchantId: undefined,
  rechargeIds: undefined,
  invoiceTitle: undefined,
  taxNumber: undefined,
  invoiceType: undefined,
  amount: undefined as number | undefined,
  status: undefined,
  contactName: undefined,
  contactPhone: undefined,
  contactEmail: undefined,
  bankName: undefined,
  bankAccount: undefined,
  companyAddress: undefined,
  companyPhone: undefined,
  invoiceCode: undefined,
  invoiceNumber: undefined,
  pdfUrl: '' as string,
  rejectReason: undefined,
  operatorId: undefined,
  operatorName: undefined,
  remark: undefined,
})
const formRules = reactive({
  merchantId: [{ required: true, message: '商家不能为空', trigger: 'change' }],
  rechargeIds: [{ required: true, message: '充值记录ID不能为空', trigger: 'blur' }],
  invoiceTitle: [{ required: true, message: '发票抬头不能为空', trigger: 'blur' }],
  taxNumber: [{ required: true, message: '税号不能为空', trigger: 'blur' }],
  invoiceType: [{ required: true, message: '发票类型不能为空', trigger: 'blur' }],
  amount: [{ required: true, message: '开票金额不能为空', trigger: 'blur' }],
  contactName: [{ required: true, message: '联系人不能为空', trigger: 'blur' }],
  contactPhone: [{ required: true, message: '联系电话不能为空', trigger: 'blur' }],
})
const formRef = ref() // 表单 Ref

/** 获取商家列表 */
const getMerchantList = async (isLoadMore = false) => {
  if (merchantLoading.value || (isLoadMore && !hasMore.value)) return
  
  if (isLoadMore) {
    loadingNewPage.value = true
  } else {
    merchantLoading.value = true
  }

  try {
    const data = await MerchantApi.getMerchantPage({
      pageNo: merchantQuery.pageNo,
      pageSize: merchantQuery.pageSize,
      merchantName: searchKeyword.value
    })
    
    if (data?.list?.length > 0) {
      merchantList.value = isLoadMore 
        ? [...merchantList.value, ...data.list]
        : data.list
      hasMore.value = data.list.length === merchantQuery.pageSize
    } else {
      if (!isLoadMore) {
        merchantList.value = []
      }
      hasMore.value = false
    }
  } catch (error) {
    console.error('获取商家列表失败:', error)
    message.error('获取商家列表失败')
    if (!isLoadMore) {
      merchantList.value = []
    }
  } finally {
    merchantLoading.value = false
    loadingNewPage.value = false
  }
}

/** 监听下拉框滚动 */
const handleDropdownScroll = throttle(async (e: Event) => {
  const target = e.target as HTMLElement
  const { scrollTop, scrollHeight, clientHeight } = target
  
  // 距离底部50px时预加载下一页
  if (scrollHeight - scrollTop - clientHeight < 50 && hasMore.value && !loadingNewPage.value) {
    merchantQuery.pageNo++
    await getMerchantList(true)
  }
}, 200)

/** 处理下拉框显示状态变化 */
const handleVisibleChange = (visible: boolean) => {
  if (visible) {
    // 下拉框显示时，添加滚动监听
    nextTick(() => {
      const dropdownWrapper = document.querySelector('.invoice-form-select-dropdown .el-select-dropdown__wrap')
      if (dropdownWrapper) {
        dropdownWrapper.addEventListener('scroll', handleDropdownScroll)
      }
    })
  } else {
    // 下拉框隐藏时，移除滚动监听
    const dropdownWrapper = document.querySelector('.invoice-form-select-dropdown .el-select-dropdown__wrap')
    if (dropdownWrapper) {
      dropdownWrapper.removeEventListener('scroll', handleDropdownScroll)
    }
  }
}

/** 处理搜索 */
const handleSearch = debounce((query: string) => {
  searchKeyword.value = query.trim()
  merchantQuery.pageNo = 1
  hasMore.value = true
  merchantList.value = []
  getMerchantList()
}, 300)

/** 处理下拉框获得焦点 */
const handleSelectFocus = () => {
  if (merchantList.value.length === 0) {
    searchKeyword.value = ''
    merchantQuery.pageNo = 1
    hasMore.value = true
    getMerchantList()
  }
}

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  
  // 重置折叠状态
  showMoreFields.value = false
  
  // 初始化商家列表
  merchantList.value = []
  hasMore.value = true
  merchantQuery.pageNo = 1
  searchKeyword.value = ''
  getMerchantList()
  
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await InvoiceRecordApi.getInvoiceRecordById(id)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as InvoiceRecordVO
    if (formType.value === 'create') {
      await InvoiceRecordApi.createInvoiceRecord(data)
      message.success(t('common.createSuccess'))
    } else {
      await InvoiceRecordApi.updateInvoiceRecord(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    merchantId: undefined,
    rechargeIds: undefined,
    invoiceTitle: undefined,
    taxNumber: undefined,
    invoiceType: undefined,
    amount: undefined,
    status: undefined,
    contactName: undefined,
    contactPhone: undefined,
    contactEmail: undefined,
    bankName: undefined,
    bankAccount: undefined,
    companyAddress: undefined,
    companyPhone: undefined,
    invoiceCode: undefined,
    invoiceNumber: undefined,
    pdfUrl: '',
    rejectReason: undefined,
    operatorId: undefined,
    operatorName: undefined,
    remark: undefined,
  }
  formRef.value?.resetFields()
}
</script>

<style lang="scss" scoped>
.merchant-select-content {
  .merchant-empty {
    padding: 20px;
    text-align: center;
  }
  
  .merchant-loading {
    padding: 8px 0;
    text-align: center;
    background-color: var(--el-bg-color);
    border-top: 1px solid var(--el-border-color-lighter);
    
    .el-icon {
      margin-right: 6px;
      font-size: 16px;
      color: var(--el-color-primary);
      vertical-align: middle;
    }
    
    .loading-text {
      font-size: 13px;
      color: var(--el-text-color-secondary);
      vertical-align: middle;
    }
  }
}

.view-more-btn {
  height: auto;
  padding: 0;
  font-size: 14px;
  color: var(--el-color-primary);
  
  .el-icon {
    margin-right: 4px;
    transition: transform 0.3s ease;
  }
  
  &:hover {
    color: var(--el-color-primary-light-3);
  }
}

.more-fields {
  padding-top: 20px;
  margin-top: 10px;
  border-top: 1px solid var(--el-border-color-lighter);
}

:deep(.el-select-dropdown__wrap) {
  max-height: 300px;
}

:deep(.el-select-dropdown__list) {
  padding: 0;
}

// 表单布局优化
.invoice-form {
  .el-row {
    margin-bottom: 10px;
  }
  
  .el-form-item {
    margin-bottom: 18px;
  }
  
  // 电子发票上传区域样式调整
  :deep(.el-upload) {
    width: 100%;
  }
  
  // 备注文本框样式
  :deep(.el-textarea__inner) {
    min-height: 80px;
    resize: vertical;
  }
}
</style>